package com.dems.remote.ali;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import com.dems.core.util.DateUtil;
import com.dems.domain.upload.FileUploadDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * 外呼
 */
@Slf4j
@Component
@RefreshScope
public class DialOssUtil {

    // LTAI5tJpaqDRrSrC2jtUnJgB
    // GsWJU8yg62gkdSH7mlwPPfKlbv7X3j
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    public static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    @Value("${ali.sms.accessKeyId}")
    private String ACCESS_KEY_ID;

    @Value("${ali.sms.accessKeySecret}")
    private String ACCESS_KEY_SECRET;

    public static final String BUCKET_DOMAIN = "sip-audio.oss-cn-shanghai.aliyuncs.com";
    public static final String BUCKET_NAME = "sip-audio";


    public String uploadDialFile(FileUploadDto fileUploadDto) {

        try {
            // 录音文件处理
            if(fileUploadDto.getFileName() == null) {
                fileUploadDto.setFileName(FilenameUtils.getName(fileUploadDto.getSipUrl().split("\\?")[0]));
            }
            String key = DateFormatUtils.format(new Date(), "yyyy/MM/dd") + "/" + fileUploadDto.getFileName();
            URL oriUrl = new URL(fileUploadDto.getSipUrl());
            HttpURLConnection conn = (HttpURLConnection)oriUrl.openConnection();
            conn.setConnectTimeout(3*1000);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " +
                    "AppleWebKit/537.36 (KHTML, like Gecko) " +
                    "Chrome/91.0.4472.114 Safari/537.36");
            conn.getInputStream();

            // 上传oss
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientConfiguration = new ClientBuilderConfiguration();
            clientConfiguration.setProtocol(Protocol.HTTPS);

            OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET, clientConfiguration);
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(BUCKET_NAME, key, conn.getInputStream());
            URL url = ossClient.generatePresignedUrl(BUCKET_NAME, key, DateUtils.addYears(new Date(), 1));
            // 关闭OSSClient。
            ossClient.shutdown();

            fileUploadDto.setOssKey(key);
            fileUploadDto.setUrl(url.toString());
            return url.toString();
        } catch (Exception e) {
            log.info("uploadDialFile error", e);
            return null;
        }
    }
}
